package com.jacky.concurrent;

import com.sun.corba.se.impl.orbutil.concurrent.Sync;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * Created by jacky on 2018/2/11.
 */
public class MyCountDownLatch {

    private final Sync sync;


    public MyCountDownLatch(int count){
        sync = new Sync(count);
    }
    static class Sync extends AbstractQueuedSynchronizer{
        public Sync(int count){
            setState(count);
        }

        /**
         * 计时器小于0的时候就会继续等待
         * @param arg
         * @return
         */
        @Override
        protected int tryAcquireShared(int arg) {
            return  getState() ==0 ?1 : -1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            for (;;){
                int state = getState();
                System.out.println("-------"+state+"---------");
                if (state == 0){
                    return  false;
                }
                int newState = state-1;
                if (compareAndSetState(state,newState)){
                    return newState==0;
                }
            }
        }
    }

    /**
     *state不为0就把线程挂起
     * @throws InterruptedException
     */
    public void await() throws InterruptedException {
     sync.acquireSharedInterruptibly(1);
    }

    /**
     * 倒时计时器减1
     */
    public void countDown(){
        sync.releaseShared(1);
    }

}
